昨天我們完成 Milvus 的基礎使用了,接著我們來介紹另一款開源的向量資料庫,今天要介紹的是 Weaviate。
Weaviate 是一個專為向量搜尋和各種 AI 應用而設計的開源向量資料庫,由Go語言從頭開發。該項目於在 BSD-3-Clause 許可下推出,正在快速堀起中。Weaviate 可以開源本地自架,也有提供雲端託管的服務。
Weaviate 的另一個特點是,可以使用 RESTful API end-points 和 GraphQL interface 來取得資料。還有 Module 的機制,例如說可以掛上我們之前提過的 sentence-transformers,讓你更方便做 embedding。連 Azure OpenAI 都可以掛上去哦!
在性能方面,可以在不到100毫秒的時間內對數百萬筆資料進行最近鄰(NN)搜索。
使用下面這個 docker compose 跑起來。可以注意裡面 ENABLE_MODULES 這段,是可以把 Azure Open AI 或是 Open AI 一起啟用。
version: '3.4'
services:
  weaviate:
    image: semitechnologies/weaviate:1.21.4
    restart: on-failure:0
    ports:
     - "8080:8080"
    volumes:
    - /var/weaviate:/var/lib/weaviate
    environment:
      QUERY_DEFAULTS_LIMIT: 20
      AUTHENTICATION_ANONYMOUS_ACCESS_ENABLED: 'true'
      PERSISTENCE_DATA_PATH: "./data"
      ENABLE_MODULES: text2vec-openai
      DEFAULT_VECTORIZER_MODULE: text2vec-openai
      CLUSTER_HOSTNAME: 'node1'
peotry add weaviate-client 。import weaviate
# 連線到資料庫
client = weaviate.Client(
    url="http://localhost:8080/",
    additional_headers={
        "X-Azure-Api-Key": "yourkey"
    }
)
print(client.is_ready())
class。而且一樣要像傳統資料庫定義 schema,雖然在 Weaviate 有個東西叫  Auto-schema ,但是官方還是建議手動定義 schema。程式碼如下:# 清除既有的 schema
client.schema.delete_all()
client.schema.get()
# 定義 schema,並且同時把 `text-embedding-ada-002` 放進去,注意`"skip": True` 就是不做 embedding 的欄位。
lyric_schema = {
    "class": "Lyric",
    "description": "A collection of lyrics",
    "vectorizer": "text2vec-openai",
    "moduleConfig": {
        "text2vec-openai": {
            "model": "ada",
            "modelVersion": "002",
            "type": "text"
        }
    },
    "properties": [{
        "name": "ids",
        "description": "Id of the lyric",
        "dataType": ["string"],
        "moduleConfig": {"text2vec-openai": {"skip": True}}
    },
        {
        "name": "lyric",
        "description": "Lyric text",
        "dataType": ["text"]
    }]
}
# add the lyric schema
client.schema.create_class(lyric_schema)
# get the schema to make sure it worked
print(client.schema.get())
data_objs = [
    {
        "ids": "A",
        "lyric": "我會披星戴月的想你,我會奮不顧身的前進,遠方煙火越來越唏噓,凝視前方身後的距離"
    },
    {
        "ids": "B",
        "lyric": "而我,在這座城市遺失了你,順便遺失了自己,以為荒唐到底會有捷徑。而我,在這座城市失去了你,輸給慾望高漲的自己,不是你,過分的感情"
    }
]
client.batch.configure(batch_size=100)  # 設定batch batch
with client.batch as batch:
    for data_obj in data_objs:
        batch.add_data_object(
            data_obj,
            "Lyric",
        )
這下子就完成 Weaviate 的操作啦!